package br.com.appwebcontroller.action;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import br.com.appwebcontroller.io.LancamentoIO;
import br.com.appwebcontroller.modelo.Lancamento;

/**
 * Servlet implementation class ControllerAction
 */
@WebServlet("/ControllerAction")
public class ControllerAction extends HttpServlet {
	private static final long serialVersionUID = 1L;

	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.processaRequisicao(request, response);
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.processaRequisicao(request, response);
	}
	
	private void processaRequisicao(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
		
		HttpSession sessao = request.getSession();
		
		List<Lancamento> lancamentos = (List<Lancamento>) sessao.getAttribute("lancamentos");
		
		String arquivo = this.getServletContext().getRealPath("/WEB-INF/lancamentos.txt");
		
		LancamentoIO io = new LancamentoIO(arquivo);
		Iterator iterator = lancamentos.iterator();
		
		while (iterator.hasNext()){
			Lancamento lancamento = (Lancamento) iterator.next();
			io.gravarRegistro(lancamento);
		}
		
		DateFormat formatado = new SimpleDateFormat("dd/MM/yyyy");
		formatado.setLenient(false);
		
		Cookie cookieUltimaGravacao = new Cookie("DataUltimaGravacao", formatado.format(new Date()));
		cookieUltimaGravacao.setMaxAge(60*60*24*7);
		
		response.addCookie(cookieUltimaGravacao);
		
		RequestDispatcher view = request.getRequestDispatcher("resultado.jsp");
		view.forward(request, response);
	}
}
